package com.financing.controller.finance;
import org.apache.shiro.authz.annotation.RequiresRoles;

import com.financing.common.CONST;
import com.financing.components.payment.Gateway;
import com.financing.components.sms.Sms;
import com.financing.enums.finance.FinanceLogType;
import com.financing.model.user.User;
import com.financing.service.finance.FinanceLogService;
import com.financing.service.finance.TransferService;
import com.financing.util.DateUtil;
import com.financing.util.Json;
import com.financing.util.Str;
import com.financing.util.XmlHelper;
import com.jfinal.core.Controller;

public class TransferController extends Controller {

	private TransferService transfer = new TransferService();
	
	/**
	 * 用户之间转账
	 * @throws Exception 
	 */
	@RequiresRoles("admin")  
	public void index() throws Exception {
		
		User operator = getAttr("user");
		User from = User.me.findById(getParaToInt("from",0));
		User to = User.me.findById(getParaToInt("to",0));
		Double amt = Double.valueOf(getParaToInt("amount"));
		String summary = getPara("summary","转账");
 
		if(from!=null && to!=null && amt>0) {
			XmlHelper res = null;
			if(Str.eq(CONST.PLAT_CODE, to.getCode()) || Str.eq(CONST.PLAT_CODE, from.getCode())) {
				res = Gateway.pay(from.getCode(), to.getCode(), amt, summary, true, false);
			}else {
				res = Gateway.pay(from.getCode(), to.getCode(), amt, summary);
			}
			if(res.isSuccess()) {
				transfer.build(from, to, amt, summary, operator);
				// 插入财务记录
				FinanceLogService.build(from, to, amt, res.getCode(), FinanceLogType.TRANSFER, summary);
				Sms.send(CONST.DEBT_MOBILE, "转账提醒："+from.getRealName()+DateUtil.getNowDateAndTime()+"向"+to.getRealName()+"成功转账"+amt+"元！");
				renderJson(Json.ok("转账成功！"));
			} else { 
				renderJson(Json.error("转账失败！"));
			}
		}else{
			renderJson(Json.error("数据不可为空！"));
		}
	}
}
 